package uk.co.droidinactu.sony.prst1.home.db;

import java.io.File;

import uk.co.droidinactu.sony.prst1.home.SonyPrsT1HomeActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * 
 * @author andy
 */
public final class SonyDatabaseController {
    private static final String DATABASE_NAME = "books.db";
    private static final String DATABASE_PATH_EXT = "/mnt/extsd/Sony_Reader/database/";
    private static final String DATABASE_PATH_INT = "/mnt/sdcard/Sony_Reader/database/";
    private static final String LOG_TAG = "SonyDatabaseController";

    private SQLiteDatabase myDBExt = null;
    private SQLiteDatabase myDBInt = null;
    public boolean useExternal = false;

    public SonyDatabaseController(final Context context) {
        super();
    }

    public void close() {
        if (this.myDBInt != null) {
            this.myDBInt.close();
            this.myDBInt = null;
        }
        if (this.myDBExt != null) {
            this.myDBExt.close();
            this.myDBExt = null;
        }
    }

    /**
     * 
     * @param sql
     * @param selectionArgs
     * @return
     */
    public Cursor execSql(final String sql, final String[] selectionArgs) {
        Cursor retCrsr = null;
        try {
            retCrsr = this.myDBInt.rawQuery(sql, selectionArgs);
        } catch (final Exception e) {
            Log.e(SonyPrsT1HomeActivity.LOG_TAG, SonyDatabaseController.LOG_TAG
                    + "Exception executing sqlite.rawQuery [" + sql + "]", e);
        }
        return retCrsr;
    }

    public void open() {
        final File dbFile = new File(SonyDatabaseController.DATABASE_PATH_INT + SonyDatabaseController.DATABASE_NAME);
        if (dbFile.exists() && this.myDBInt == null) {
            this.myDBInt = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);
        }
        final File dbFile2 = new File(SonyDatabaseController.DATABASE_PATH_EXT + SonyDatabaseController.DATABASE_NAME);
        if (dbFile2.exists() && this.myDBExt == null) {
            this.myDBInt.execSQL("attach database '" + dbFile2.getAbsolutePath() + "' as extDb");
            this.myDBExt = SQLiteDatabase.openDatabase(dbFile2.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);
        }
    }
}
